package zhongche.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.zhongche.bean.DataTypeInfo;
import com.zhongche.bean.Nodes;

import java.util.ArrayList;
import java.util.List;

public class TransObjUtil {

    private static final String ID = "id";
    private static final String ATTRIBUTES = "attributes";
    private static final String TYPE = "type";
    private static final String VALUE = "value";
    private static final String OUTPUT = "output";
    private static final String INPUT = "input";
    private static final String DESCRIPTION = "description";
    private static final String DATA_TYPE = "dataType";
    private static final String SHAPE = "shape";
    private static final String LABEL = "label";


    /**
     * JSONObject 转 Nodes
     * @param jsonObject
     * @return
     */
    public static Nodes transJSONObjToNodes(JSONObject jsonObject){
        Nodes nodes = new Nodes();
        nodes.setId(jsonObject.getString(ID));
        JSONObject attributes = jsonObject.getJSONObject(ATTRIBUTES);
        nodes.setDescription(attributes.getString(DESCRIPTION));
        nodes.setType(attributes.getString(TYPE));
        nodes.setValue(attributes.getString(VALUE));
        nodes.setDataType(attributes.getString(DATA_TYPE));
        nodes.setShape(jsonObject.getString(SHAPE));
        nodes.setLabel(jsonObject.getString(LABEL));
        JSONArray jsonArrayInput = attributes.getJSONArray(INPUT);
        JSONArray jsonArrayOutput = attributes.getJSONArray(OUTPUT);
        List<DataTypeInfo> inputList = parseJsonArrayToDataTyInfoList(jsonArrayInput,DataTypeInfo.class);
        List<DataTypeInfo> outputList = parseJsonArrayToDataTyInfoList(jsonArrayOutput,DataTypeInfo.class);
        nodes.setInput(inputList);
        nodes.setOutput(outputList);
        return nodes;
    }


    /**
     * JSONArray 转java bean
     * @param jsonArray
     * @param clz
     * @param <T>
     * @return
     */
    public static <T>List<T> parseJsonArrayToDataTyInfoList(JSONArray jsonArray, Class<T> clz){
        if(jsonArray == null){
            return null;
        }
        List<T> infoList = new ArrayList<>();
        for (Object obj: jsonArray) {
            JSONObject jsObj = (JSONObject) obj;
            infoList.add(JSONObject.parseObject(jsObj.toJSONString(),clz));
        }
        return  infoList;
    }
}
